import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    //客户端自己的socket
    private Socket socket = null;

    public TcpEchoClient(String ip, int port) throws IOException {
        //指定服务器的地址和端口号
        socket = new Socket(ip, port);
    }

    public void start(){
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            Scanner scannerConsole = new Scanner(System.in);
            while(true){
                //1.组织请求
                String request = scannerConsole.next();
                //2.将请求发送给服务器
                PrintWriter writer = new PrintWriter(outputStream);
                writer.println(request);
                writer.flush();
                //3.接受服务器端的响应
                Scanner scannerResponse = new Scanner(inputStream);
                String response = scannerResponse.next();
                System.out.println(response);

            }
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1", 8080);
        client.start();
    }
}
